<template>
    <div class="department-selector">
      <label>部门：</label>
      <el-checkbox-group v-model="selectedDepartments" @change="emitSelectedDepartments">
        <el-checkbox
          v-for="department in departmentList"
          :key="department.selfid"
          :label="department.dept_name"
        >
          {{ department.dept_name }}
        </el-checkbox>
      </el-checkbox-group>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { ref, computed, onMounted, defineEmits, watch } from 'vue';
  import { useDepartmentStore } from '@/stores/department';
  
  const emit = defineEmits(['update:selectedDepartments']);
  const departmentStore = useDepartmentStore();
  const selectedDepartments = ref<string[]>([]);
  
  // 获取部门列表
  const departmentList = computed(() => {
    const flattenDepartments = (departments) => {
        let result = [];
        departments.forEach(department => {
            result.push(department);
            if (department.childs && department.childs.length > 0) {
                result = result.concat(flattenDepartments(department.childs));
            }
        });
        return result;
    };
    return flattenDepartments(departmentStore.departmentList);
  });
  
  // 在组件挂载时获取部门数据
  onMounted(() => {
    departmentStore.fetchDepartmentList();
  });
  
  // 发出选择的部门
  const emitSelectedDepartments = () => {
    emit('update:selectedDepartments', selectedDepartments.value);
  };
  
  // 监听 selectedDepartments 的变化
  watch(selectedDepartments, emitSelectedDepartments);
  </script>
  
  <style scoped>
  .department-selector {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .department-selector label {
    margin-right: 10px;
    white-space: nowrap;
  }
  
  /* 添加间距样式 */
  .el-checkbox {
    margin-right: 20px !important; /* 调整每个部门项的间距 */
  }
  </style>